﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Business;
using EntitiesTM;
using System.Text;
using System.IO;

namespace TimeWork.report
{
    public partial class ReportActivityManager : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["email"] == null)
            {
                Response.Redirect("http://"+Request.Url.Authority+"/Login.aspx");
            }
            if (!IsPostBack)
            {
                ddlActivity.Visible = false;
                fillData();
            }
        }

        protected void ddlTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlMonth.Visible = false;
            lblStart.Visible = false;
            lblEnd.Visible = false;
            txtEndTime.Visible = false;
            txtStartTime.Visible = false;
            switch (Int32.Parse(ddlTime.SelectedValue))
            {
                case 1:
                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 5:
                    ddlMonth.Visible = true;
                    break;
                case 6:
                    break;
                case 7:
                    lblStart.Visible = true;
                    lblEnd.Visible = true;
                    txtEndTime.Visible = true;
                    txtStartTime.Visible = true;
                    break;
            }
        }

        private void BindDdlProject()
        {
            Dictionary<string, string> data = BuProject.selProjectByParentIDTreeReport(0, Session["companyid"].ToString());
            ListItem item;
            item = new ListItem("Tất cả sản phẩm","0");
            ddlproject.Items.Add(item);

            foreach (KeyValuePair<string, string> pair in data)
            {
                item = new ListItem(pair.Value,pair.Key);
                ddlproject.Items.Add(item);
            }
        }

        protected void ddlproject_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!ddlproject.SelectedValue.Equals("0"))
            {
                int projectLevel = BuProject.selProjectByIDTree(Int32.Parse(ddlproject.SelectedValue), Session["companyid"].ToString()).projectLevel;
                if (projectLevel == 3)
                {
                    // Cho hien DropDownList activity va do du lieu
                    ddlActivity.Visible = true;
                    EnProject project = new EnProject();
                    project.projectID = Int32.Parse(ddlproject.SelectedValue);
                    ddlActivity.DataSource = BuProject.selActivityByProjectExceptID(project, Session["companyid"].ToString());
                    ddlActivity.DataTextField = "ActivityName";
                    ddlActivity.DataValueField = "ActivityID";
                    ddlActivity.DataBind();
                    ddlActivity.Items.Insert(0, new ListItem("Tất cả công việc", "0"));
                    ddlActivity.SelectedValue = "0";
                }
                else
                {
                    ddlActivity.Visible = false;
                }
                string value = ddlActivity.SelectedValue;
            }
            else
            {
                ddlActivity.Visible = false;
            }
        }
        public void fillData()
        {
            BindDdlProject();

            ddlUser.DataSource = BuStaff.selAllStaffOptByResultUnit(Session["email"].ToString(), Session["companyid"].ToString());
            ddlUser.DataTextField = "StaffName";
            ddlUser.DataValueField = "StaffID";
            ddlUser.DataBind();
            ddlUser.Items.Insert(0, new ListItem("Tất cả người dùng", "0"));
            ddlUser.SelectedValue = "0";

            ddlClient.DataSource = BuClient.selAllClient(Session["companyid"].ToString());
            ddlClient.DataTextField = "ClientName";
            ddlClient.DataValueField = "ClientID";
            ddlClient.DataBind();
            ddlClient.Items.Insert(0, new ListItem("Tất cả đối tác", "0"));
            ddlClient.SelectedValue = "0";

            ddlResultUnit.DataSource = BuResultUnit.selAllResultUnit(Session["companyid"].ToString());
            ddlResultUnit.DataTextField = "ResultUnitName";
            ddlResultUnit.DataValueField = "ResultUnitID";
            ddlResultUnit.DataBind();
            ddlResultUnit.Items.Insert(0, new ListItem("Tất cả đơn vị", "0"));
            ddlResultUnit.SelectedValue = "0";

            ddlTypeTime.DataSource = BuProject.selAllTypeTime(Session["companyid"].ToString());
            ddlTypeTime.DataTextField = "TypeTimeName";
            ddlTypeTime.DataValueField = "TypeTimeID";
            ddlTypeTime.DataBind();
            ddlTypeTime.Items.Insert(0, new ListItem("Tất cả loại thời giờ", "0"));
            ddlTypeTime.SelectedValue = "0";
        }

        public void getParam()
        {
            try
            {
                string companyid = Session["companyid"].ToString();
                int project = Int32.Parse(ddlproject.SelectedValue);

                string time = ddlTime.SelectedValue;
                DateTime start = DateTime.Now;
                DateTime end = DateTime.Now;
                if (time.Equals("7"))
                {
                    start = DateTime.ParseExact(txtStartTime.Text, "d/M/yyyy", null);
                    end = DateTime.ParseExact(txtEndTime.Text, "d/M/yyyy", null);
                }

                int month = Int32.Parse(ddlMonth.SelectedValue);
                int user = Int32.Parse(ddlUser.SelectedValue);
                int client = Int32.Parse(ddlClient.SelectedValue);
                int resultUnit = Int32.Parse(ddlResultUnit.SelectedValue);
                int typeTime = Int32.Parse(ddlTypeTime.SelectedValue);
                bool enableClient = cbClient.Checked;
                DateTime date = DateTime.Now;
                string sql = String.Empty;
                if (enableClient)
                {
                    sql += "SELECT ProjectName, ActivityName,StaffName, ClientName, SUM(SAReportTimeHour) 'Hour', SUM(SAReportTimeMinute) 'Minute'" +
                            " FROM VTK_SA" + companyid + " INNER JOIN VTK_Activity" + companyid + " ON SAActivityID = ActivityID INNER JOIN VTK_Project" + companyid + " ON ActivityProjectID = ProjectID INNER JOIN VTK_Staff" + companyid + " ON SAStaffID = StaffID INNER JOIN VTK_TypeTime" + companyid + " ON SATypeTimeID = TypeTimeID LEFT JOIN VTK_Client" + companyid + " ON ProjectClientID = ClientID ";
                }
                else
                {
                    sql += "SELECT ProjectName, ActivityName,StaffName, SUM(SAReportTimeHour) 'Hour', SUM(SAReportTimeMinute) 'Minute'" +
                           " FROM VTK_SA" + companyid + " INNER JOIN VTK_Activity" + companyid + " ON SAActivityID = ActivityID INNER JOIN VTK_Project" + companyid + " ON ActivityProjectID = ProjectID INNER JOIN VTK_Staff" + companyid + " ON SAStaffID = StaffID INNER JOIN VTK_TypeTime" + companyid + " ON SATypeTimeID = TypeTimeID LEFT JOIN VTK_Client" + companyid + " ON ProjectClientID = ClientID ";
                }
                if (time.Equals("1"))
                {
                    sql += "WHERE CONVERT(varchar(10),SADate,101) = CONVERT(varchar(10),CAST('" + date + "' AS DATETIME), 101) ";
                }
                if (time.Equals("2"))
                {
                    sql += "WHERE CONVERT(varchar(10),SADate,101) = CONVERT(varchar(10),CAST(DATEADD(DD,-1,'" + date + "') AS DATETIME), 101) ";
                }
                if (time.Equals("3"))
                {
                    sql += "WHERE DATEPART(MM,'" + date + "') = DATEPART(MM,SADate) ";
                }
                if (time.Equals("4"))
                {
                    sql += "WHERE DATEPART(MM,'" + date + "')-1 = DATEPART(MM,SADate) ";
                }
                if (time.Equals("5"))
                {
                    sql += "WHERE DATEPART(MM,SADate) = " + month + " ";
                }
                if (time.Equals("6"))
                {
                    sql += "WHERE 1 = 1 ";
                }
                if (time.Equals("7"))
                {
                    sql += "WHERE CONVERT(varchar(10),SADate,101) >= CONVERT(varchar(10),CAST('" + start + "' AS DATETIME), 101) AND CONVERT(varchar(10),SADate,101) <= CONVERT(varchar(10),CAST('" + end + "' AS DATETIME), 101) ";
                }

                if (project != 0)
                {
                    // Neu project != 0 thi phai them dieu kien
                    int projectLevel = BuProject.selProjectByIDTree(Int32.Parse(ddlproject.SelectedValue), Session["companyid"].ToString()).projectLevel;
                    // Truong hop level = 3 thi xuat hien lua chon cong viec
                    if (projectLevel == 3)
                    {
                        // Truong hop chon tat ca
                        if (ddlActivity.SelectedValue.Equals("0"))
                        {
                            sql += "AND ProjectID = " + project + " ";
                        }
                        // Neu chi chon lua 01 activity
                        else
                        {
                            sql += "AND SAActivityID = " + ddlActivity.SelectedValue + " ";
                        }
                    }
                    if (projectLevel == 2)
                    {
                        sql += "AND ProjectID IN (SELECT ProjectID FROM VTK_Project" + companyid + " WHERE ProjectParentID =  " + project + ") ";
                    }
                    if (projectLevel == 1)
                    {
                        sql += "AND ProjectID IN (SELECT ProjectID FROM VTK_Project" + companyid + " WHERE ProjectParentID IN (SELECT ProjectID FROM VTK_Project" + companyid + " WHERE ProjectParentID =  " + project + ")) ";
                    }

                }
                int resultUnitID = BuStaff.selResultUnitIDByEmail(Session["email"].ToString(), Session["companyid"].ToString());
                // Truong hop khong ton tai resultUnit
                if (resultUnitID == 0)
                {
                    // Chi show bao cao ca nhan
                    int staffID = BuStaff.selStaffIDByEmail(Session["email"].ToString(), Session["companyid"].ToString());
                    sql += "AND SAStaffID = " + staffID + " ";
                }
                else
                {
                    if (user != 0)
                    {
                        sql += "AND SAStaffID = " + user + " ";
                    }
                    else
                    {
                        sql += "AND StaffResultUnitID = " + resultUnitID + " ";
                    }

                }
                if (client != 0)
                {
                    sql += "AND ClientID = " + client + " ";
                }

                //if (resultUnit != 0)
                //{
                //    sql += "AND StaffResultUnitID = " + resultUnit + " ";
                //}

                if (typeTime != 0)
                {
                    sql += "AND TypeTimeID = " + typeTime + " ";
                }
                sql += "AND (SAReportTimeHour!=0 OR SAReportTimeMinute!=0) ";
                if (enableClient)
                {
                    sql += "GROUP BY ActivityName, ProjectName, StaffName, ClientName ORDER BY ProjectName";
                }
                else
                {
                    sql += "GROUP BY ActivityName, ProjectName, StaffName ORDER BY ProjectName";
                }

                lblData.Text = String.Empty;
                DataTable data = BuReport.selReportDetailed(sql);
                if (data.Rows.Count > 0)
                {
                    gvReport.DataSource = data;
                }
                else
                {
                    lblData.Text = "Chưa có dữ liệu";
                }
                gvReport.DataBind();

            }
            catch { }
        }

        protected void btnGenerate_Click(object sender, EventArgs e)
        {
            getParam();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            return;
        }
        protected void btnExportExcel_Click(object sender, ImageClickEventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AppendHeader("Content-Disposition", "attachment;filename=BaoCaoTheoCongViec" + DateTime.
            Now.ToString("yyyyMMdd") + ".xls");
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "application/ms-excel";
            this.EnableViewState = false;

            var sb = new StringBuilder();
            getParam();gvReport.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
            Response.Write(sb.ToString());
            Response.End();
        }

        string previousName;
        int firstRow;
        int rowColor = 0;
        //string previousProject;
        protected void gvReport_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {   //We're only interested in Rows that contain data
                //get a reference to the data used to databound the row
                DataRowView drv = ((DataRowView)e.Row.DataItem);


                if (previousName == drv[1].ToString())
                {
                    //If it's the same category as the previous one
                    //Increment the rowspan
                    if (gvReport.Rows[firstRow].Cells[1].RowSpan == 0)

                        gvReport.Rows[firstRow].Cells[1].RowSpan = 2;
                    else
                        gvReport.Rows[firstRow].Cells[1].RowSpan += 1;
                    //Remove the cell
                    e.Row.Cells.RemoveAt(1);
                }
                else //It's a new category
                {
                    //Set the vertical alignment to top
                    e.Row.VerticalAlign = VerticalAlign.Top;
                    //Maintain the category in memory
                    previousName = drv[1].ToString();
                    firstRow = e.Row.RowIndex;
                    rowColor++;
                }

                /////////////////////////////////////////////
                strPreviousRowID = drv["ActivityName"].ToString();

                double dblDirectRevenue = Convert.ToDouble(drv["Hour"].ToString());
                double dblReferralRevenue = Convert.ToDouble(drv["Minute"].ToString());

                dblSubTotalDirectRevenue += dblDirectRevenue;
                dblSubTotalReferralRevenue += dblReferralRevenue;

                dblGrandTotalDirectRevenue += dblDirectRevenue;
                dblGrandTotalReferralRevenue += dblReferralRevenue;
            }
        }

        // To keep track of the previous row Group Identifier
        string strPreviousRowID = string.Empty;
        // To keep track the Index of Group Total
        int intSubTotalIndex = 1;

        // To temporarily store Sub Total
        double dblSubTotalDirectRevenue = 0;
        double dblSubTotalReferralRevenue = 0;

        // To temporarily store Grand Total
        double dblGrandTotalDirectRevenue = 0;
        double dblGrandTotalReferralRevenue = 0;
        protected void gvReport_RowCreated(object sender, GridViewRowEventArgs e)
        {
            DataRowView drv = ((DataRowView)e.Row.DataItem);

            bool IsSubTotalRowNeedToAdd = false;
            bool IsGrandTotalRowNeedtoAdd = false;

            if ((strPreviousRowID != string.Empty) && (DataBinder.Eval(e.Row.DataItem, "ActivityName") != null))
                if (strPreviousRowID != DataBinder.Eval(e.Row.DataItem, "ActivityName").ToString())
                    IsSubTotalRowNeedToAdd = true;

            if ((strPreviousRowID != string.Empty) && (DataBinder.Eval(e.Row.DataItem, "ActivityName") == null))
            {
                IsSubTotalRowNeedToAdd = true;
                IsGrandTotalRowNeedtoAdd = true;
                intSubTotalIndex = 0;
            }

            if (IsSubTotalRowNeedToAdd)
            {
                GridView grdViewProducts = (GridView)sender;

                // Creating a Row
                GridViewRow SubTotalRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert);

                //Adding Total Cell 
                TableCell HeaderCell = new TableCell();
                HeaderCell.Text = "Cộng";
                HeaderCell.HorizontalAlign = HorizontalAlign.Left;
                HeaderCell.ColumnSpan = 3; // For merging first, second row cells to one
                HeaderCell.CssClass = "SubTotalRowStyle SubTotalRowStyle-add";
                SubTotalRow.Cells.Add(HeaderCell);

                // Quy doi thoi gian
                int minute = (int)dblSubTotalReferralRevenue;
                if (minute >= 60)
                {
                    int addHour = minute / 60;
                    minute -= addHour * 60;
                    dblSubTotalReferralRevenue = minute;
                    dblSubTotalDirectRevenue += addHour;
                }

                //Adding Direct Revenue Column
                HeaderCell = new TableCell();
                HeaderCell.Text = string.Format("{0:0}", dblSubTotalDirectRevenue);
                HeaderCell.HorizontalAlign = HorizontalAlign.Right;
                HeaderCell.CssClass = "SubTotalRowStyle";
                SubTotalRow.Cells.Add(HeaderCell);

                //Adding Referral Revenue Column
                HeaderCell = new TableCell();
                HeaderCell.Text = string.Format("{0:0}", dblSubTotalReferralRevenue);
                HeaderCell.HorizontalAlign = HorizontalAlign.Right;
                HeaderCell.CssClass = "SubTotalRowStyle";
                SubTotalRow.Cells.Add(HeaderCell);


                //Adding the Row at the RowIndex position in the Grid
                gvReport.Controls[0].Controls.AddAt(e.Row.RowIndex + intSubTotalIndex, SubTotalRow);
                intSubTotalIndex++;

                dblSubTotalDirectRevenue = 0;
                dblSubTotalReferralRevenue = 0;
            }
            if (IsGrandTotalRowNeedtoAdd)
            {
                GridView grdViewProducts = (GridView)sender;

                // Creating a Row
                GridViewRow GrandTotalRow = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Insert);

                //Adding Total Cell 
                TableCell HeaderCell = new TableCell();
                HeaderCell.Text = "Tổng cộng";
                HeaderCell.HorizontalAlign = HorizontalAlign.Left;
                HeaderCell.ColumnSpan = 3; // For merging first, second row cells to one
                HeaderCell.CssClass = "GrandTotalRowStyle GrandTotalRowStyle-add";
                GrandTotalRow.Cells.Add(HeaderCell);

                // Quy doi thoi gian
                int minute = (int)dblGrandTotalReferralRevenue;
                if (minute >= 60)
                {
                    int addHour = minute / 60;
                    minute -= addHour * 60;
                    dblGrandTotalReferralRevenue = minute;
                    dblGrandTotalDirectRevenue += addHour;
                }

                //Adding Direct Revenue Column
                HeaderCell = new TableCell();
                HeaderCell.Text = string.Format("{0:0}", dblGrandTotalDirectRevenue);
                HeaderCell.HorizontalAlign = HorizontalAlign.Right;
                HeaderCell.CssClass = "GrandTotalRowStyle";
                GrandTotalRow.Cells.Add(HeaderCell);

                //Adding Referral Revenue Column
                HeaderCell = new TableCell();
                HeaderCell.Text = string.Format("{0:0}", dblGrandTotalReferralRevenue);
                HeaderCell.HorizontalAlign = HorizontalAlign.Right;
                HeaderCell.CssClass = "GrandTotalRowStyle";
                GrandTotalRow.Cells.Add(HeaderCell);

                //Adding the Row at the RowIndex position in the Grid
                gvReport.Controls[0].Controls.AddAt(e.Row.RowIndex, GrandTotalRow);
            }
        }
    }
}